package com.css.zfzx.fwsjcj.modules.structure.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.components.attach.repository.entity.SysAttachmentEntity;
import com.css.bpm.platform.components.attach.service.SysAttachment;
import com.css.bpm.platform.org.division.repository.entity.DivisionEntity;
import com.css.bpm.platform.org.user.repository.entity.UserEntity;
import com.css.bpm.platform.utils.PlatformObjectUtils;
import com.css.bpm.platform.utils.PlatformSessionUtils;
import com.css.bpm.platform.utils.UUIDGenerator;
import com.css.zfzx.fwsjcj.cache.DivisionCache;
import com.css.zfzx.fwsjcj.commen.util.Constant;
import com.css.zfzx.fwsjcj.commen.util.EasyPoiExcelUtil;
import com.css.zfzx.fwsjcj.modules.analysis.vo.AnalysisQueryVo;
import com.css.zfzx.fwsjcj.modules.structure.entity.FwStoneStructureEntity;
import com.css.zfzx.fwsjcj.modules.structure.entity.FwStructureFormEntity;
import com.css.zfzx.fwsjcj.modules.structure.entity.QFwStoneStructureEntity;
import com.css.zfzx.fwsjcj.modules.structure.repository.FwStoneStructureRepository;
import com.css.zfzx.fwsjcj.modules.structure.repository.FwStructureFormRepository;
import com.css.zfzx.fwsjcj.modules.structure.service.FwStoneStructureService;
import com.css.zfzx.fwsjcj.modules.structure.service.FwStructureFormService;
import com.css.zfzx.fwsjcj.modules.structure.verify.BrickStructureCheck;
import com.css.zfzx.fwsjcj.modules.structure.verify.StoneStructureCheck;
import com.css.zfzx.fwsjcj.modules.structure.vo.FwStoneStructureVo;
import com.css.zfzx.fwsjcj.modules.structure.vo.StructureQueryVo;
import com.querydsl.core.QueryResults;
import com.querydsl.core.types.ExpressionUtils;
import com.querydsl.core.types.Predicate;
import com.querydsl.jpa.impl.JPAQueryFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author leon
 * @Title: FwStoneStructureServiceImpl
 * @Description:
 * @date 2020/6/4 14:29
 */
@Slf4j
@Service
public class FwStoneStructureServiceImpl implements FwStoneStructureService {
    @Autowired
    private FwStoneStructureRepository stoneStructureRepository;
    @Autowired
    private JPAQueryFactory jpaQueryFactory;
    @Autowired
    private FwStructureFormService structureFormService;
    @Autowired
    private FwStructureFormRepository fwStructureFormRepository;
    @Resource
    private SysAttachment sysAttachment;

    private volatile static HashMap<String, List> divisionMap;

    @Override
    @Transactional
    public void save(FwStoneStructureEntity fwStoneStructureEntity) {
        String userId = PlatformSessionUtils.getUserId();
        UserEntity user = PlatformAPI.getOrgAPI().getUserAPI().getUser(userId);
        /**
         * 砖石结构子表设置默认值（子表保存）
         */
        fwStoneStructureEntity.setId(UUIDGenerator.getUUID());
        // 数据收集人名称
        fwStoneStructureEntity.setCollectUser(user.getUserName());
        // 存数据收集人ID
        fwStoneStructureEntity.setCreateUser(userId);
        fwStoneStructureEntity.setCreateTime(new Date());
        fwStoneStructureEntity.setDelFlag(Constant.DEL_NO);
        stoneStructureRepository.save(fwStoneStructureEntity);

        /**
         * 主表保存
         */
        FwStructureFormEntity structureFormEntity = new FwStructureFormEntity();
        // 保存子表ID
        structureFormEntity.setStructureId(fwStoneStructureEntity.getId());
        // 保存子表类型
        structureFormEntity.setStructureType(Constant.STONE_STRUCTURE);
        // 保存子表省、市、区县
        structureFormEntity.setBelongtoProvince(fwStoneStructureEntity.getBelongtoProvince());
        structureFormEntity.setBelongtoCity(fwStoneStructureEntity.getBelongtoCity());
        structureFormEntity.setBelongtoArea(fwStoneStructureEntity.getBelongtoArea());
        // 保存子表建筑名称
        structureFormEntity.setBuildingName(fwStoneStructureEntity.getBuildingName());
        // 保存子表建筑类型
        structureFormEntity.setSiteType(fwStoneStructureEntity.getSiteType());
        // 保存建筑编号
        structureFormEntity.setStructureNum(fwStoneStructureEntity.getStoneStructureNum());
        // 保存任务id和名称
        structureFormEntity.setTaskId(fwStoneStructureEntity.getTaskId());
        structureFormEntity.setTaskName(fwStoneStructureEntity.getTaskName());
        structureFormEntity.setBuildingArea(fwStoneStructureEntity.getBuildingArea()==null?0.0:fwStoneStructureEntity.getBuildingArea());
        structureFormEntity.setStatus(fwStoneStructureEntity.getStatus());
        structureFormService.save(structureFormEntity);
    }

    @Override
    @Transactional
    public void update(FwStoneStructureEntity fwStoneStructureEntity) {
        if (StringUtils.isEmpty(fwStoneStructureEntity.getId())) {
            throw new RuntimeException("修改ID不能为空");
        }
        // 获取当前用户信息
        String userId = PlatformSessionUtils.getUserId();
        UserEntity user = PlatformAPI.getOrgAPI().getUserAPI().getUser(userId);
        /**
         * 设置默认值
         */
        fwStoneStructureEntity.setUpdateUser(user.getUserId());
        fwStoneStructureEntity.setUpdateTime(new Date());
        // 将不为空的数据拷贝到旧数据中
        //FwStoneStructureEntity oldTarge = this.findById(fwStoneStructureEntity.getId());
        //  若审核状态为审核未通过改为未提交
        if(Constant.SP_NOT.equals(fwStoneStructureEntity.getStatus())){
            fwStoneStructureEntity.setStatus(Constant.NO_SUB);
            fwStoneStructureEntity.setCheckOpinion("");
            fwStoneStructureEntity.setCheckUser("");
        }
        //SpringUtil.copyPropertiesIgnoreEmpty(fwStoneStructureEntity, oldTarge);
        // 实体中必须有ID
        stoneStructureRepository.save(fwStoneStructureEntity);

        /**
         * 主表保存
         */
        FwStructureFormEntity sourceStructureFormEntity = structureFormService.findStructureForm(Constant.STONE_STRUCTURE, fwStoneStructureEntity.getId());
        //FwStructureFormEntity targetStructureFormEntity = sourceStructureFormEntity;
        // 保存子表省
        sourceStructureFormEntity.setBelongtoProvince(fwStoneStructureEntity.getBelongtoProvince());
        // 保存子表市
        sourceStructureFormEntity.setBelongtoCity(fwStoneStructureEntity.getBelongtoCity());
        // 保存子表区县
        sourceStructureFormEntity.setBelongtoArea(fwStoneStructureEntity.getBelongtoArea());
        // 保存子表建筑名称
        sourceStructureFormEntity.setBuildingName(fwStoneStructureEntity.getBuildingName());
        // 保存子表建筑类型
        sourceStructureFormEntity.setSiteType(fwStoneStructureEntity.getSiteType());
        // 若审核状态为审核未通过改为未提交
        if (Constant.SP_NOT.equals(sourceStructureFormEntity.getStatus())){
            sourceStructureFormEntity.setStatus(Constant.NO_SUB);
            sourceStructureFormEntity.setCheckUser("");
            sourceStructureFormEntity.setCheckOpinion("");
        }
        sourceStructureFormEntity.setStatus(fwStoneStructureEntity.getStatus());
        sourceStructureFormEntity.setBuildingArea(fwStoneStructureEntity.getBuildingArea()==null?0.0:fwStoneStructureEntity.getBuildingArea());
        structureFormService.update(sourceStructureFormEntity);
    }

    @Override
    public JSONObject getPage(StructureQueryVo structureQueryVo, int curPage, int pageSize) {
        QFwStoneStructureEntity q = QFwStoneStructureEntity.fwStoneStructureEntity;
        Predicate predicate = q.isNotNull().or(q.isNull());

        // 查询条件
        if (structureQueryVo != null) {
            String buildingName = structureQueryVo.getBuildingName();
            predicate = ("".equals(buildingName) || buildingName == null) ? predicate : ExpressionUtils.and(predicate, q.buildingName.like("%" + buildingName + "%"));

            String belongtoProvince = structureQueryVo.getBelongtoProvince();
            predicate = ("".equals(belongtoProvince) || belongtoProvince == null) ? predicate : ExpressionUtils.and(predicate, q.belongtoProvince.like("%" + belongtoProvince + "%"));

            String belongtoCity = structureQueryVo.getBelongtoCity();
            predicate = ("".equals(belongtoCity) || belongtoCity == null) ? predicate : ExpressionUtils.and(predicate, q.belongtoCity.like("%" + belongtoCity + "%"));

            String siteType = structureQueryVo.getSiteType();
            predicate = ("".equals(siteType) || siteType == null) ? predicate : ExpressionUtils.and(predicate, q.siteType.like("%" + siteType + "%"));

            String status = structureQueryVo.getStatus();
            predicate = ("".equals(status) || status == null) ? predicate : ExpressionUtils.and(predicate, q.status.eq(status));

        }
        // 删除标识
        predicate = ExpressionUtils.and(predicate, q.delFlag.eq(Constant.DEL_NO));

        QueryResults<FwStoneStructureEntity> page = jpaQueryFactory
                .selectFrom(q)
                .where(predicate)
                .orderBy(q.createTime.desc())
                .offset(curPage - 1)   //起始页
                .limit(pageSize)  //每页大小
                .fetchResults();
        /**
         * 适配base转为JSONObject类型
         */
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("rows", page.getResults());
        jsonObject.put("total", page.getTotal());
        return jsonObject;
    }

    @Override
    public void delete(String id) {
        FwStoneStructureEntity stoneStructureEntity = stoneStructureRepository.findById(id).get();
        stoneStructureEntity.setDelFlag(Constant.DEL_YES);
        update(stoneStructureEntity);
    }

    @Override
    public FwStoneStructureEntity findById(String id) {
        return stoneStructureRepository.findById(id).get();
    }

    @Override
    public List<FwStoneStructureEntity> findAll() {
        return stoneStructureRepository.findAll();
    }

    @Override
    @Transactional
    public void submit(List<String> idList) {
        QFwStoneStructureEntity q = QFwStoneStructureEntity.fwStoneStructureEntity;
        jpaQueryFactory.update(q)
                .set(q.status, Constant.DAI_SP)
                .where(q.id.in(idList))
                .execute();
    }

    public HashMap<String, List> divisionMap() {
        HashMap<String, List> map = new HashMap<>();
        // 所有省
        List<DivisionEntity> provinceDivisions = PlatformAPI.getDivisionAPI().getSubDivisions("root");
        for (DivisionEntity province : provinceDivisions) {
            String provinceName = province.getDivisionName();
            // 市
            List<DivisionEntity> cities = PlatformAPI.getDivisionAPI().getSubDivisions(province.getDivisionId());
            ArrayList<String> cityNames = new ArrayList<>();
            for (DivisionEntity city : cities) {
                String cityName = city.getDivisionName();
                cityNames.add(cityName);
                // 不为直辖市
                if (!"北京市".equals(provinceName) && !"天津市".equals(provinceName) && !"上海市".equals(provinceName) && !"重庆市".equals(provinceName)) {
                    // 获取市下面的区县
                    List<DivisionEntity> areas = PlatformAPI.getDivisionAPI().getSubDivisions(city.getDivisionId());
                    ArrayList<String> areaNames = new ArrayList<>();
                    for (DivisionEntity area : areas) {
                        String areaName = area.getDivisionName();
                        areaNames.add(areaName);
                    }
                    map.put(cityName, areaNames);
                }
            }
            // 省对应下面的市(直辖市-对应的是区)
            map.put(provinceName, cityNames);
        }
        return map;
    }

    @Override
    public String exportExcel(String taskName, String taskId, MultipartFile file, HttpServletResponse response) {
        // 单例初始化省市区map
        if (divisionMap == null) {
            synchronized (this) {
                if (divisionMap == null) {
                    divisionMap = divisionMap();
                }
            }
        }
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            params.setVerifyHandler(new StoneStructureCheck(divisionMap));
            // 获取到Excel数据
            ExcelImportResult<FwStoneStructureVo> result = ExcelImportUtil.importExcelMore(file.getInputStream(), FwStoneStructureVo.class, params);
            List<FwStoneStructureVo> list = result.getList();
            // Excel条数据
            int firstList = list.size();
            StringBuilder sb = new StringBuilder();
            // 重复后失败条数
            int failCount = saveFwStrucure(taskName, taskId, list, sb);
            if (failCount > 0) {
                // result.getFailList().size()为保存时出错的条数
                int failList = firstList + result.getFailList().size() - list.size();
                returnMsg.append("成功导入" + (result.getList().size() - failCount) + "条，失败" + (failList + failCount) + "条<br/>");
                returnMsg.append("样本编码" + failCount + "存在重复数据<br/>");
                returnMsg.append(sb);
            } else {
                returnMsg.append("成功导入" + (result.getList().size() - failCount) + "条，失败" + (result.getFailList().size() + failCount) + "条<br/>");
                returnMsg.append(sb);
            }
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<FwStoneStructureVo> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    FwStoneStructureVo fwStoneStructureVo = iterator.next();
                    String error = "";
                    returnMsg.append("第" + fwStoneStructureVo.getRowNum() + "行" + fwStoneStructureVo.getErrorMsg() + "<br/>");
                    returnMsg.append(error);
                }
            }
            return returnMsg.toString();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return "导入失败，请检查数据正确性";
        }
    }

    @Transactional
    @Override
    public void updateFileId(String formId, String fileId) {
        FwStoneStructureEntity fwStoneStructureEntity = findById(formId);

        if (!StringUtils.isEmpty(fwStoneStructureEntity)) {
            stoneStructureRepository.updateFile(formId, fileId);
        }
    }

    @Override
    public double area(AnalysisQueryVo analysisQueryVo) {
        Specification<FwStoneStructureEntity> specification = new Specification<FwStoneStructureEntity>() {
            @Override
            public javax.persistence.criteria.Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<javax.persistence.criteria.Predicate> predicates = new ArrayList<>();
                if (analysisQueryVo != null) {
                    // 省
                    String belongtoProvince = analysisQueryVo.getBelongtoProvince();
                    if (!StringUtils.isEmpty(belongtoProvince)) {
                        predicates.add(criteriaBuilder.equal(root.get("belongtoProvince"), belongtoProvince));
                    }
                    // 市
                    String belongtoCity = analysisQueryVo.getBelongtoCity();
                    if (!StringUtils.isEmpty(belongtoCity)) {
                        predicates.add(criteriaBuilder.equal(root.get("belongtoCity"), belongtoCity));
                    }
                    // 区
                    String belongtoArea = analysisQueryVo.getBelongtoArea();
                    if (!StringUtils.isEmpty(belongtoArea)) {
                        predicates.add(criteriaBuilder.equal(root.get("belongtoArea"), belongtoArea));
                    }
                    //建筑年代
                    String buildingAge = analysisQueryVo.getBuildingAge();
                    if (!org.apache.commons.lang3.StringUtils.isEmpty(buildingAge)) {
                        predicates.add(criteriaBuilder.equal(root.get("buildingAge"), buildingAge));
                    }
                    //任务名称
                    String taskName = analysisQueryVo.getTaskName();
                    if (!org.apache.commons.lang3.StringUtils.isEmpty(taskName)) {
                        String[] strArray = taskName.split(",");
                        List<String> list = Arrays.asList(strArray);
                        if (list != null && list.size() > 0){
                            predicates.add(root.get("taskName").in(list));
                        }
                    }
                    /*//抗震设防烈度
                    String nowFortificationIntensity = analysisQueryVo.getNowFortificationIntensity();
                    if (!org.apache.commons.lang3.StringUtils.isEmpty(nowFortificationIntensity)) {
                        predicates.add(criteriaBuilder.equal(root.get("fortifyStandard"), nowFortificationIntensity));
                    }*/
                    // 墙体材质(石或斜石,加工块石,毛石,其他)
                    String wallMaterial = analysisQueryVo.getWallMaterial();
                    if (!StringUtils.isEmpty(wallMaterial)) {
                        predicates.add(criteriaBuilder.equal(root.get("wallMaterial"), wallMaterial));
                    }
                    // 横墙最大间距
                    String hqzdSpace = analysisQueryVo.getHqzdSpace();
                    if (!StringUtils.isEmpty(hqzdSpace)) {
                        if (Constant.LESS_3.equals(hqzdSpace)) {
                            predicates.add(criteriaBuilder.le(root.get("hqzdSpace"), 3));
                        }
                        if (Constant.BETWEEN_3_5.equals(hqzdSpace)) {
                            predicates.add(criteriaBuilder.between(root.get("hqzdSpace"), 3, 5));
                        }
                        if (Constant.BETWEEN_5_7.equals(hqzdSpace)) {
                            predicates.add(criteriaBuilder.between(root.get("hqzdSpace"), 5, 7));
                        }
                        if (Constant.BETWEEN_7_9.equals(hqzdSpace)) {
                            predicates.add(criteriaBuilder.between(root.get("hqzdSpace"), 7, 9));
                        }
                        if (Constant.MORE_9.equals(hqzdSpace)) {
                            predicates.add(criteriaBuilder.ge(root.get("hqzdSpace"), 9));
                        }
                    }
                    // 墙体厚度（按照≤120mm，120-240mm，240-360mm，≥360mm统计占比）
                    String wallThick = analysisQueryVo.getWallThick();
                    if (!StringUtils.isEmpty(wallThick)) {
                        if (Constant.LESS_120.equals(wallThick)) {
                            predicates.add(criteriaBuilder.le(root.get("wallThick"), 120));
                        }
                        if (Constant.BETWEEN_120_240.equals(wallThick)) {
                            predicates.add(criteriaBuilder.between(root.get("wallThick"), 120, 240));
                        }
                        if (Constant.BETWEEN_240_360.equals(wallThick)) {
                            predicates.add(criteriaBuilder.between(root.get("wallThick"), 240, 360));
                        }
                        if (Constant.MORE_360.equals(wallThick)) {
                            predicates.add(criteriaBuilder.ge(root.get("wallThick"), 360));
                        }
                    }
                    //横墙开洞面积(大于水平全截面1/3,小于水平全截面1/3)
                    String hqkdArea = analysisQueryVo.getHqkdArea();
                    if (!StringUtils.isEmpty(hqkdArea)) {
                        predicates.add(criteriaBuilder.like(root.get("hqkdArea"), hqkdArea));
                    }
                    // 屋盖类型(木屋架,预制板,彩钢屋架,其他)
                    String roofType = analysisQueryVo.getRoofType();
                    if (!StringUtils.isEmpty(roofType)) {
                        predicates.add(criteriaBuilder.like(root.get("roofType"), roofType));
                    }
                    // 石结构：圈梁(有圈梁,无圈梁)
                    String ql = analysisQueryVo.getQl();
                    if (!StringUtils.isEmpty(ql)) {
                        predicates.add(criteriaBuilder.like(root.get("ql"), ql));
                    }
                    // 四角设构造柱 0（无）,1（有）
                    String sjsgzz = analysisQueryVo.getSjsgzz();
                    if (!StringUtils.isEmpty(sjsgzz)) {
                        predicates.add(criteriaBuilder.like(root.get("sjsgzz"), sjsgzz));
                    }
                }
                // 有效标识，即为有效的
                predicates.add(criteriaBuilder.equal(root.get("delFlag"), Constant.DEL_NO));
                // 只查询审核通过，状态为3
                predicates.add(criteriaBuilder.equal(root.get("status"), Constant.SP_YES));
                return criteriaBuilder.and(predicates.toArray(new javax.persistence.criteria.Predicate[predicates.size()]));

            }
        };
        double count = 0.00;
        List<FwStoneStructureEntity> stoneStructureEntityList = stoneStructureRepository.findAll(specification);
        for (FwStoneStructureEntity stoneStructureEntity : stoneStructureEntityList) {
            double buildingAreaCount = 0.00;
            // 建筑面积
            if (!PlatformObjectUtils.isEmpty(stoneStructureEntity.getBuildingArea())) {
                buildingAreaCount = stoneStructureEntity.getBuildingArea().doubleValue();
                if (!PlatformObjectUtils.isEmpty(stoneStructureEntity.getFloorNum())) {
                    buildingAreaCount = stoneStructureEntity.getBuildingArea().doubleValue() *
                            stoneStructureEntity.getFloorNum().intValue();
                }
            }
            count += buildingAreaCount;
        }
        Double.parseDouble(String.format("%.3f", count));
        return Double.parseDouble(String.format("%.3f", count));
    }

    @Override
    public long count(AnalysisQueryVo analysisQueryVo) {
        Specification<FwStoneStructureEntity> specification = new Specification<FwStoneStructureEntity>() {
            @Override
            public javax.persistence.criteria.Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<javax.persistence.criteria.Predicate> predicates = new ArrayList<>();
                if (analysisQueryVo != null) {
                    // 省
                    String belongtoProvince = analysisQueryVo.getBelongtoProvince();
                    if (!StringUtils.isEmpty(belongtoProvince)) {
                        predicates.add(criteriaBuilder.equal(root.get("belongtoProvince"), belongtoProvince));
                    }
                    // 市
                    String belongtoCity = analysisQueryVo.getBelongtoCity();
                    if (!StringUtils.isEmpty(belongtoCity)) {
                        predicates.add(criteriaBuilder.equal(root.get("belongtoCity"), belongtoCity));
                    }
                    // 区
                    String belongtoArea = analysisQueryVo.getBelongtoArea();
                    if (!StringUtils.isEmpty(belongtoArea)) {
                        predicates.add(criteriaBuilder.equal(root.get("belongtoArea"), belongtoArea));
                    }
                    //建筑年代
                    String buildingAge = analysisQueryVo.getBuildingAge();
                    if (!org.apache.commons.lang3.StringUtils.isEmpty(buildingAge)) {
                        predicates.add(criteriaBuilder.equal(root.get("buildingAge"), buildingAge));
                    }
                    //任务名称
                    String taskName = analysisQueryVo.getTaskName();
                    if (!org.apache.commons.lang3.StringUtils.isEmpty(taskName)) {
                        String[] strArray = taskName.split(",");
                        List<String> list = Arrays.asList(strArray);
                        if (list != null && list.size() > 0){
                            predicates.add(root.get("taskName").in(list));
                        }
                    }
                    /*//抗震设防烈度
                    String nowFortificationIntensity = analysisQueryVo.getNowFortificationIntensity();
                    if (!org.apache.commons.lang3.StringUtils.isEmpty(nowFortificationIntensity)) {
                        predicates.add(criteriaBuilder.equal(root.get("fortifyStandard"), nowFortificationIntensity));
                    }*/
                    // 墙体材质(石或斜石,加工块石,毛石,其他)
                    String wallMaterial = analysisQueryVo.getWallMaterial();
                    if (!StringUtils.isEmpty(wallMaterial)) {
                        predicates.add(criteriaBuilder.equal(root.get("wallMaterial"), wallMaterial));
                    }
                    // 横墙最大间距
                    String hqzdSpace = analysisQueryVo.getHqzdSpace();
                    if (!StringUtils.isEmpty(hqzdSpace)) {
                        if (Constant.LESS_3.equals(hqzdSpace)) {
                            predicates.add(criteriaBuilder.le(root.get("hqzdSpace"), 3));
                        }
                        if (Constant.BETWEEN_3_5.equals(hqzdSpace)) {
                            predicates.add(criteriaBuilder.between(root.get("hqzdSpace"), 3, 5));
                        }
                        if (Constant.BETWEEN_5_7.equals(hqzdSpace)) {
                            predicates.add(criteriaBuilder.between(root.get("hqzdSpace"), 5, 7));
                        }
                        if (Constant.BETWEEN_7_9.equals(hqzdSpace)) {
                            predicates.add(criteriaBuilder.between(root.get("hqzdSpace"), 7, 9));
                        }
                        if (Constant.MORE_9.equals(hqzdSpace)) {
                            predicates.add(criteriaBuilder.ge(root.get("hqzdSpace"), 9));
                        }
                    }
                    // 墙体厚度（按照≤120mm，120-240mm，240-360mm，≥360mm统计占比）
                    String wallThick = analysisQueryVo.getWallThick();
                    if (!StringUtils.isEmpty(wallThick)) {
                        if (Constant.LESS_120.equals(wallThick)) {
                            predicates.add(criteriaBuilder.le(root.get("wallThick"), 120));
                        }
                        if (Constant.BETWEEN_120_240.equals(wallThick)) {
                            predicates.add(criteriaBuilder.between(root.get("wallThick"), 120, 240));
                        }
                        if (Constant.BETWEEN_240_360.equals(wallThick)) {
                            predicates.add(criteriaBuilder.between(root.get("wallThick"), 240, 360));
                        }
                        if (Constant.MORE_360.equals(wallThick)) {
                            predicates.add(criteriaBuilder.ge(root.get("wallThick"), 360));
                        }
                    }
                    //横墙开洞面积(大于水平全截面1/3,小于水平全截面1/3)
                    String hqkdArea = analysisQueryVo.getHqkdArea();
                    if (!StringUtils.isEmpty(hqkdArea)) {
                        predicates.add(criteriaBuilder.like(root.get("hqkdArea"), hqkdArea));
                    }
                    // 屋盖类型(木屋架,预制板,彩钢屋架,其他)
                    String roofType = analysisQueryVo.getRoofType();
                    if (!StringUtils.isEmpty(roofType)) {
                        predicates.add(criteriaBuilder.like(root.get("roofType"), roofType));
                    }
                    // 石结构：圈梁(有圈梁,无圈梁)
                    String ql = analysisQueryVo.getQl();
                    if (!StringUtils.isEmpty(ql)) {
                        predicates.add(criteriaBuilder.like(root.get("ql"), ql));
                    }
                    // 四角设构造柱 0（无）,1（有）
                    String sjsgzz = analysisQueryVo.getSjsgzz();
                    if (!StringUtils.isEmpty(sjsgzz)) {
                        predicates.add(criteriaBuilder.like(root.get("sjsgzz"), sjsgzz));
                    }
                }
                // 有效标识，即为有效的
                predicates.add(criteriaBuilder.equal(root.get("delFlag"), Constant.DEL_NO));
                // 只查询审核通过，状态为3
                predicates.add(criteriaBuilder.equal(root.get("status"), Constant.SP_YES));
                return criteriaBuilder.and(predicates.toArray(new javax.persistence.criteria.Predicate[predicates.size()]));

            }
        };
        return stoneStructureRepository.count(specification);
    }

    @Override
    public int areaCount(AnalysisQueryVo analysisQueryVo) {
        Specification<FwStoneStructureEntity> specification = new Specification<FwStoneStructureEntity>() {
            @Override
            public javax.persistence.criteria.Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<javax.persistence.criteria.Predicate> predicates = new ArrayList<>();
                if (analysisQueryVo != null) {
                    // 省
                    String belongtoProvince = analysisQueryVo.getBelongtoProvince();
                    if (!StringUtils.isEmpty(belongtoProvince)) {
                        predicates.add(criteriaBuilder.equal(root.get("belongtoProvince"), belongtoProvince));
                    }
                    // 市
                    String belongtoCity = analysisQueryVo.getBelongtoCity();
                    if (!StringUtils.isEmpty(belongtoCity)) {
                        predicates.add(criteriaBuilder.equal(root.get("belongtoCity"), belongtoCity));
                    }
                    // 区
                    String belongtoArea = analysisQueryVo.getBelongtoArea();
                    if (!StringUtils.isEmpty(belongtoArea)) {
                        predicates.add(criteriaBuilder.equal(root.get("belongtoArea"), belongtoArea));
                    }
                    // 墙体材质(石或斜石,加工块石,毛石,其他)
                    String wallMaterial = analysisQueryVo.getWallMaterial();
                    if (!StringUtils.isEmpty(wallMaterial)) {
                        predicates.add(criteriaBuilder.equal(root.get("wallMaterial"), wallMaterial));
                    }
                    // 横墙最大间距
                    String hqzdSpace = analysisQueryVo.getHqzdSpace();
                    if (!StringUtils.isEmpty(hqzdSpace)) {
                        if (Constant.LESS_3.equals(hqzdSpace)) {
                            predicates.add(criteriaBuilder.le(root.get("hqzdSpace"), 3));
                        }
                        if (Constant.BETWEEN_3_5.equals(hqzdSpace)) {
                            predicates.add(criteriaBuilder.between(root.get("hqzdSpace"), 3, 5));
                        }
                        if (Constant.BETWEEN_5_7.equals(hqzdSpace)) {
                            predicates.add(criteriaBuilder.between(root.get("hqzdSpace"), 5, 7));
                        }
                        if (Constant.BETWEEN_7_9.equals(hqzdSpace)) {
                            predicates.add(criteriaBuilder.between(root.get("hqzdSpace"), 7, 9));
                        }
                        if (Constant.MORE_9.equals(hqzdSpace)) {
                            predicates.add(criteriaBuilder.ge(root.get("hqzdSpace"), 9));
                        }
                    }
                    // 墙体厚度（按照≤120mm，120-240mm，240-360mm，≥360mm统计占比）
                    String wallThick = analysisQueryVo.getWallThick();
                    if (!StringUtils.isEmpty(wallThick)) {
                        if (Constant.LESS_120.equals(wallThick)) {
                            predicates.add(criteriaBuilder.le(root.get("wallThick"), 120));
                        }
                        if (Constant.BETWEEN_120_240.equals(wallThick)) {
                            predicates.add(criteriaBuilder.between(root.get("wallThick"), 120, 240));
                        }
                        if (Constant.BETWEEN_240_360.equals(wallThick)) {
                            predicates.add(criteriaBuilder.between(root.get("wallThick"), 240, 360));
                        }
                        if (Constant.MORE_360.equals(wallThick)) {
                            predicates.add(criteriaBuilder.ge(root.get("wallThick"), 360));
                        }
                    }
                    //横墙开洞面积(大于水平全截面1/3,小于水平全截面1/3)
                    String hqkdArea = analysisQueryVo.getHqkdArea();
                    if (!StringUtils.isEmpty(hqkdArea)) {
                        predicates.add(criteriaBuilder.like(root.get("hqkdArea"), hqkdArea));
                    }
                    // 屋盖类型(木屋架,预制板,彩钢屋架,其他)
                    String roofType = analysisQueryVo.getRoofType();
                    if (!StringUtils.isEmpty(roofType)) {
                        predicates.add(criteriaBuilder.like(root.get("roofType"), roofType));
                    }
                    // 石结构：圈梁(有圈梁,无圈梁)
                    String ql = analysisQueryVo.getQl();
                    if (!StringUtils.isEmpty(ql)) {
                        predicates.add(criteriaBuilder.like(root.get("ql"), ql));
                    }
                    // 四角设构造柱 0（无）,1（有）
                    String sjsgzz = analysisQueryVo.getSjsgzz();
                    if (!StringUtils.isEmpty(sjsgzz)) {
                        predicates.add(criteriaBuilder.like(root.get("sjsgzz"), sjsgzz));
                    }
                }
                // 有效标识，即为有效的
                predicates.add(criteriaBuilder.equal(root.get("delFlag"), Constant.DEL_NO));
                // 只查询审核通过，状态为3
                predicates.add(criteriaBuilder.equal(root.get("status"), Constant.SP_YES));
                return criteriaBuilder.and(predicates.toArray(new javax.persistence.criteria.Predicate[predicates.size()]));

            }
        };
        int count = 0;
        List<FwStoneStructureEntity> stoneStructureEntityList = stoneStructureRepository.findAll(specification);
        for (FwStoneStructureEntity stoneStructureEntity : stoneStructureEntityList) {
            int buildingAreaCount = 0;
            // 建筑面积
            Double buildingArea = stoneStructureEntity.getBuildingArea();
            if (buildingArea != null && !StringUtils.isEmpty(buildingArea.toString())) {
                buildingAreaCount = stoneStructureEntity.getBuildingArea().intValue();
            }
            count += buildingAreaCount;
        }
        return count;
    }

    @Override
    public void export(List<String> idList, HttpServletResponse response) {
        List<FwStoneStructureEntity> list = stoneStructureRepository.findInIdList(idList);
        // 深拷贝
        ArrayList<FwStoneStructureVo> vos = new ArrayList<>();
        for (FwStoneStructureEntity stoneStructureEntity : list) {
            if(stoneStructureEntity.getStatus().equals("1")){
                stoneStructureEntity.setStatus("未审核");
            }else if(stoneStructureEntity.getStatus().equals("2")){
                stoneStructureEntity.setStatus("审核未通过");
            }else if(stoneStructureEntity.getStatus().equals("3")){
                stoneStructureEntity.setStatus("审核通过");
            }else if(stoneStructureEntity.getStatus().equals("4")){
                stoneStructureEntity.setStatus("省级退回");
            }else {
                stoneStructureEntity.setStatus("中心退回");
            }
            String detailFile = stoneStructureEntity.getDetailFile();
            StringBuilder file = new StringBuilder();
            if(org.apache.commons.lang3.StringUtils.isNotBlank(detailFile)){
                //获取数据真实的附件信息
                List<SysAttachmentEntity> byAttachIdsAndIsValid = sysAttachment.findByAttachIdsAndIsValid(Arrays.asList(detailFile.split(",")));
                if(PlatformObjectUtils.isNotEmpty(byAttachIdsAndIsValid)){
                    for (SysAttachmentEntity sysAttachmentEntity : byAttachIdsAndIsValid) {
                        String attachPath = sysAttachmentEntity.getAttachPath();
                        attachPath = attachPath.replace("/","");
                        file.append(attachPath).append(",");
                    }
                }
            }
            if(file.length()>0){
                String fileName = file.substring(0, file.length() - 1);
                stoneStructureEntity.setDetailFile(fileName);
            }
            FwStoneStructureVo vo = new FwStoneStructureVo();
            BeanUtils.copyProperties(stoneStructureEntity, vo);
            vos.add(vo);
        }
        // 导出
        EasyPoiExcelUtil.exportExcel(vos, "石结构信息统计", "石结构信息", FwStoneStructureVo.class, "石结构.xls", response);
    }


    public int saveFwStrucure(String taskName, String taskId, List<FwStoneStructureVo> list, StringBuilder message) {
        int count = 0;
        for (int i = 0; i < list.size(); i++) {
            FwStoneStructureEntity stoneStructure = new FwStoneStructureEntity();
            FwStoneStructureVo stoneStructureVo = list.get(i);
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(stoneStructureVo, stoneStructure);
            String delflag="0";
            // 根据样本编号判断重复导入性
            FwStoneStructureEntity byStoneStructureNum = stoneStructureRepository.findByStoneStructureNumAndDelFlag(stoneStructureVo.getStoneStructureNum(),delflag);
            if (!StringUtils.isEmpty(byStoneStructureNum)) {
                message.append("样本编码" + stoneStructureVo.getStoneStructureNum() + "已重复");
                ++count;
            } else {
                stoneStructure.setTaskId(taskId);
                stoneStructure.setTaskName(taskName);
                //导入数据后台生成编号
                String code = DivisionCache.structureCode();
                stoneStructure.setStoneStructureNum(code);
                save(stoneStructure);
            }
        }
        return count;
    }


    @Override
    public long buildingCount(AnalysisQueryVo analysisQueryVo) {
        Specification<FwStructureFormEntity> specification = new Specification<FwStructureFormEntity>() {
            @Override
            public javax.persistence.criteria.Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<javax.persistence.criteria.Predicate> predicates = new ArrayList<>();
                if (analysisQueryVo != null) {
                    // 省
                    String belongtoProvince = analysisQueryVo.getBelongtoProvince();
                    if (!StringUtils.isEmpty(belongtoProvince)) {
                        predicates.add(criteriaBuilder.equal(root.get("belongtoProvince"), belongtoProvince));
                    }
                    // 市
                    String belongtoCity = analysisQueryVo.getBelongtoCity();
                    if (!StringUtils.isEmpty(belongtoCity)) {
                        predicates.add(criteriaBuilder.equal(root.get("belongtoCity"), belongtoCity));
                    }
                    // 区
                    String belongtoArea = analysisQueryVo.getBelongtoArea();
                    if (!StringUtils.isEmpty(belongtoArea)) {
                        predicates.add(criteriaBuilder.equal(root.get("belongtoArea"), belongtoArea));
                    }
                    //建筑年代
                    String buildingAge = analysisQueryVo.getBuildingAge();
                    if (!org.apache.commons.lang3.StringUtils.isEmpty(buildingAge)) {
                        predicates.add(criteriaBuilder.equal(root.get("buildingAge"), buildingAge));
                    }
                    //任务名称
                    String taskName = analysisQueryVo.getTaskName();
                    if (!org.apache.commons.lang3.StringUtils.isEmpty(taskName)) {
                        String[] strArray = taskName.split(",");
                        List<String> list = Arrays.asList(strArray);
                        if (list != null && list.size() > 0){
                            predicates.add(root.get("taskName").in(list));
                        }
                    }
                    // 审批类型
                    String status = analysisQueryVo.getStatus();
                    if (!StringUtils.isEmpty(status)) {
                        if ("审核通过".equals(status)) {
                            // 若为审核通过，查询status状态为3
                            predicates.add(criteriaBuilder.equal(root.get("status"), Constant.SP_YES));
                        } else if ("审核不通过".equals(status)) {
                            // 若为审核不通过，查询status状态为2
                            predicates.add(criteriaBuilder.equal(root.get("status"), Constant.SP_NOT));
                        } else {
                            //若为审核不通过，查询status状态为2
                            predicates.add(criteriaBuilder.equal(root.get("status"), Constant.DAI_SP));
                        }
                    }else {
                        //默认查询非未提交的
                        //predicates.add(criteriaBuilder.in(root.get("status"), (Constant.DAI_SP,Constant.DAI_SP));
                        CriteriaBuilder.In<Object> in = criteriaBuilder.in(root.get("status"));
                        in.value(Constant.DAI_SP);
                        in.value(Constant.SP_NOT);
                        in.value(Constant.SP_YES);
                        predicates.add(in);
                    }
                }
                // 有效标识，即为有效的
                predicates.add(criteriaBuilder.equal(root.get("delFlag"), Constant.DEL_NO));
                // 只查询审核通过，状态为3
                //predicates.add(criteriaBuilder.equal(root.get("status"), Constant.SP_YES));
                predicates.add(criteriaBuilder.equal(root.get("structureType"), Constant.STONE_STRUCTURE));
                return criteriaBuilder.and(predicates.toArray(new javax.persistence.criteria.Predicate[predicates.size()]));

            }
        };
        return fwStructureFormRepository.count(specification);
    }


    @Override
    public double stoneAreaCount(AnalysisQueryVo analysisQueryVo) {
        Specification<FwStoneStructureEntity> specification = new Specification<FwStoneStructureEntity>() {
            @Override
            public javax.persistence.criteria.Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<javax.persistence.criteria.Predicate> predicates = new ArrayList<>();
                if (analysisQueryVo != null) {
                    // 省
                    String belongtoProvince = analysisQueryVo.getBelongtoProvince();
                    if (!StringUtils.isEmpty(belongtoProvince)) {
                        predicates.add(criteriaBuilder.equal(root.get("belongtoProvince"), belongtoProvince));
                    }
                    // 市
                    String belongtoCity = analysisQueryVo.getBelongtoCity();
                    if (!StringUtils.isEmpty(belongtoCity)) {
                        predicates.add(criteriaBuilder.equal(root.get("belongtoCity"), belongtoCity));
                    }
                    // 区
                    String belongtoArea = analysisQueryVo.getBelongtoArea();
                    if (!StringUtils.isEmpty(belongtoArea)) {
                        predicates.add(criteriaBuilder.equal(root.get("belongtoArea"), belongtoArea));
                    }
                    //建筑年代
                    String buildingAge = analysisQueryVo.getBuildingAge();
                    if (!org.apache.commons.lang3.StringUtils.isEmpty(buildingAge)) {
                        predicates.add(criteriaBuilder.equal(root.get("buildingAge"), buildingAge));
                    }
                    //任务名称
                    String taskName = analysisQueryVo.getTaskName();
                    if (!org.apache.commons.lang3.StringUtils.isEmpty(taskName)) {
                        predicates.add(criteriaBuilder.equal(root.get("taskName"), taskName));
                    }
                    /*//抗震设防烈度
                    String nowFortificationIntensity = analysisQueryVo.getNowFortificationIntensity();
                    if (!org.apache.commons.lang3.StringUtils.isEmpty(nowFortificationIntensity)) {
                        predicates.add(criteriaBuilder.equal(root.get("fortifyStandard"), nowFortificationIntensity));
                    }*/
                    // 审批类型
                    String status = analysisQueryVo.getStatus();
                    if (!StringUtils.isEmpty(status)) {
                        if ("审核通过".equals(status)) {
                            // 若为审核通过，查询status状态为3
                            predicates.add(criteriaBuilder.equal(root.get("status"), Constant.SP_YES));
                        } else if ("审核不通过".equals(status)) {
                            // 若为审核不通过，查询status状态为2
                            predicates.add(criteriaBuilder.equal(root.get("status"), Constant.SP_NOT));
                        } else {
                            //若为审核不通过，查询status状态为2
                            predicates.add(criteriaBuilder.equal(root.get("status"), Constant.DAI_SP));
                        }
                    }else {
                        //默认查询非未提交的
                        //predicates.add(criteriaBuilder.in(root.get("status"), (Constant.DAI_SP,Constant.DAI_SP));
                        CriteriaBuilder.In<Object> in = criteriaBuilder.in(root.get("status"));
                        in.value(Constant.DAI_SP);
                        in.value(Constant.SP_NOT);
                        in.value(Constant.SP_YES);
                        predicates.add(in);
                    }
                }
                // 有效标识，即为有效的
                predicates.add(criteriaBuilder.equal(root.get("delFlag"), Constant.DEL_NO));
                // 只查询审核通过，状态为3
                //predicates.add(criteriaBuilder.equal(root.get("status"), Constant.SP_YES));
                return criteriaBuilder.and(predicates.toArray(new javax.persistence.criteria.Predicate[predicates.size()]));

            }
        };
        int count = 0;
        List<FwStoneStructureEntity> stoneStructureEntityList = stoneStructureRepository.findAll(specification);
        for (FwStoneStructureEntity stoneStructureEntity : stoneStructureEntityList) {
            int buildingAreaCount = 0;
            // 建筑面积
            Double buildingArea = stoneStructureEntity.getBuildingArea();
            if (buildingArea != null && !StringUtils.isEmpty(buildingArea.toString())) {
                buildingAreaCount = stoneStructureEntity.getBuildingArea().intValue();
            }
            count += buildingAreaCount;
        }
        return count;
    }

}
